/*
 * @Author: huangxuzhong
 * @Date: 2021-09-23 15:49:10
 * @LastEditTime: 2023-03-30
 * @LastEditors: Tommy Chen
 * @Description: 消息推送框架
 * @FilePath: /macc.admin.vue/src/plugin/iframeMessage/iframeMessage.js
 */
export default {
  install(Vue) {
    //监听消息map
    window.IFARMEMESSAGE = {};
    window.IFARMECALLBACK = {};
    //注册消息推送
    window.addEventListener(
      'message',
      function (e) {
        if (
          e.data &&
          e.data.comtedEvent &&
          typeof window.IFARMEMESSAGE[e.data.comtedEvent] == 'function'
        ) {
          window.IFARMEMESSAGE[e.data.comtedEvent](e.data.comtedData);
          return;
        }

        if (e.data && e.data.action && e.data.action == 'LOGIN_OUT') {
          console.log('子框架收到登出信息');
          location.href = '/webproxy/sso/logout';
          return;
        }

        if (e.data && e.data.callback) {
          const event = e.data.callback.event;
          const params = e.data.callback.params;
          typeof window.IFARMECALLBACK[event] == 'function' &&
            window.IFARMECALLBACK[event](params);
        }
      },
      window.location.origin
    );

    /**
     * @description: temp: intl_public 的作用。国内内嵌是会触发iframeMessage，有了这个参数，则直接跳转路由
     * @param {*} moduleId
     * @param {*} options
     * @return {*}
     */
    Vue.prototype.$iframeMsg = function (moduleId, options) {
      if (window === window.top) {
        switch (moduleId) {
          case 'REGISTER_COMTED': {
            if (options.eventName) {
              console.log('vue MQTT消息订阅', options.eventName);
              this.$EventBus.$on(options.eventName, (data) => {
                console.log('vue MQTT接收消息', options.eventName, data);
                typeof options.comtedCallback == 'function' &&
                  options.comtedCallback(data);
              });
            }
            break;
          }
          case 'GOTO_HASH': {
            if (options.groupId) {
              this.$store.commit('Group/SET_GROUPID', options.groupId);
            }
            this.$router.replace({ path: '/' + options.hash });
            break;
          }
        }
      } else {
        //判断是否是注册comted事件
        if (moduleId == 'REGISTER_COMTED' && options.eventName) {
          window.IFARMEMESSAGE[options.eventName] = options.comtedCallback;
          window.parent.postMessage(
            { module: moduleId, options: { eventName: options.eventName } },
            window.location.origin
          );
        } else {
          if (options?.temp && window.top?.base?.mpm === 'intl_public') {
            if (options.groupId) {
              this.$store.commit('Group/SET_GROUPID', options.groupId);
            }
            this.$router.replace({ path: '/' + options.hash });
          } else {
            window.parent.postMessage(
              { module: moduleId, options: options },
              window.location.origin
            );
          }
        }
      }
    };
  },
};
